package cn.windy.samary.module.shiro.controller;

import cn.windy.samary.core.annotation.OpLog;
import cn.windy.samary.module.admin.common.Tree;
import cn.windy.samary.module.admin.entity.Permission;
import cn.windy.samary.module.admin.entity.User;
import cn.windy.samary.module.admin.service.IUserService;
import cn.windy.samary.module.abstracts.controller.AbstractController;
import cn.windy.samary.module.shiro.realm.CustomShiroRealm;
import cn.windy.samary.utils.ShiroUtils;
import cn.windy.samary.module.shiro.UserTypeToken;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyl
 * @date 2018/5/12 17:26
 */
@Controller
@RequestMapping
public class IndexController extends AbstractController {

    @Resource
    private IUserService userService;

    @OpLog("用户打开登录页或进行登陆")
    @RequestMapping("/login")
    public String loginTo(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vs = request.getParameter("vs");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            if (StringUtils.isNotBlank(vs)) {
                model.addAttribute("msg", "用户名或密码不能为空！");
            }
            return "/admin/login";
        }
        Subject subject = SecurityUtils.getSubject();
        Md5Hash md5Hash = new Md5Hash(password, username, 10);
        UserTypeToken token = new UserTypeToken(username, md5Hash.toString(), "0");
        try {
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("msg", "用户名或密码错误！");
            return "/admin/login";
        }


        return "redirect:/admin/index";
    }

    @OpLog("打开系统主页")
    @RequestMapping("admin/index")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
        String userId = ShiroUtils.getUserId();
        User user1 = userService.selectByPrimaryKey(userId);
        if (user1 == null) {
            return "/admin/login";
        }

        List<String> roleStrings = userService.getRoleStringByUserId(user1.getId());

        if (roleStrings.size() == 0) {
            return "redirect:/403";
        }

        List<Tree<Permission>> trees = userService.initMenu(user1.getId());
        model.addAttribute("adminUser", user1);
        model.addAttribute("menus", trees);
        return "admin/index";
    }

    @OpLog("打开首页")
    @GetMapping("admin/home")
    public String home() {
        return "admin/home";
    }

    /**
     * 返回前台页面
     *
     * @param path 路径参数，多级路径以"_"分开
     * @return 起始地址为根路径
     */
    @GetMapping(value = "/getrpage/{path}")
    public Object getrpage(HttpServletRequest request, HttpServletResponse response,
                           Model model, @PathVariable("path") String path) {
        String p = path.replaceAll("_", "/");
        return "/" + p;
    }

    @OpLog("退出登陆")
    @RequestMapping("logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = ShiroUtils.getSubject();
        subject.logout();
        return "redirect:/admin/index";
    }

    @RequestMapping(value = "/403", produces = "text/html")
    public String handle403Html(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "/403";
    }

    @ResponseBody
    @RequestMapping(value = "/403")
    public Object handle403(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 403);
        map.put("msg", "无权访问！");
        return map;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("11111", "tttt", 10);
        System.out.println(md5Hash);
    }

}
